package com.openingedu.mba.screen.fragment;

import java.util.List;

import net.umipay.android.UmiPaySDKManager;
import net.umipay.android.UmiPaymentInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.lurencun.android.support.widget.CommonAdapter;
import com.openingedu.mba.R;
import com.openingedu.mba.common.AppSetting;
import com.openingedu.mba.common.CommConsts;
import com.openingedu.mba.persist.DbOrder;
import com.openingedu.mba.screen.adapter.OrderAdapter;
import com.openingedu.mba.service.OrderService;
import com.openingedu.mba.service.task.TaskInvoker;
import com.openingedu.mba.service.task.TaskQueue;
import com.openingedu.mba.service.task.impl.TaskCheckOrder;

/**
 * 
 * 消息
 * 
 * @author unidw
 */
public class FragmentOrder extends SherlockFragment {

	private Context mContext;
	private ListView listView;
	private List<DbOrder> orderList;
	private CommonAdapter<DbOrder> orderAdapter;
	private OrderService orderService;
	private Button payAllBtn;
	
	private boolean showPayNotify = false;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		LinearLayout orderLayout = (LinearLayout)inflater.inflate(R.layout.ft_order, container, false);
		mContext = orderLayout.getContext();
		orderService = new OrderService();
		TextView listEmptyView = (TextView) orderLayout.findViewById(R.id.listEmptyView);
		listView = (ListView) orderLayout.findViewById(R.id.list_container);
		payAllBtn = (Button) orderLayout.findViewById(R.id.pay_all_btn);
		orderAdapter = new OrderAdapter(mContext);
		orderList = orderService.listOrder(mContext);
		orderAdapter.updateDataCache(orderList);
		listView.setAdapter(orderAdapter);
		listView.setEmptyView(listEmptyView);
		payAllBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 订单列表为空
				if (orderList == null && orderList.size() == 0 ) {
					Toast.makeText(mContext, mContext.getResources().getString(R.string.str_order_list_is_empty), Toast.LENGTH_LONG).show();
				}
				else {
					if (!AppSetting.UMIPAY_INITIALIZED) {
						Toast.makeText(mContext, "很抱歉，支付框架未能初始化成功，请检查网络后重启客户端支付。", Toast.LENGTH_LONG).show();
						return;
					}
					int orderNum = 0;
					StringBuffer buf = new StringBuffer();
					buf.append("DID-");
					Double totalPay = 0.00;
					for (DbOrder order : orderList) {
						// 未支付订单
						if (order.getOrderStatus() == CommConsts.Order.NONE_PAID) {
							if (orderNum != 0) {
								buf.append(",");
							}
							buf.append(order.getOrderDID());
							orderNum++;
							totalPay = totalPay + order.getOrderPrice();
						}
					}
					if (orderNum > 0) {
						showPayConfirm(orderNum, totalPay, buf.toString());
					}
				}
			}
		});
		launchCheckTask();
		return orderLayout;
	}
	
	private void showPayConfirm(final int orderNum, final Double totalPay, final String orderStr) {
		Toast.makeText(mContext, orderStr, Toast.LENGTH_LONG).show();
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
		alertDialog.setTitle("提示");
		alertDialog.setMessage("确定为[" + orderNum + "]个订单支付[" + totalPay + "]RMB吗？");
		alertDialog.setPositiveButton("取消",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int which) {
					}
				});
		alertDialog.setNegativeButton("确定",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int which) {
						pay(totalPay, orderStr);
					}
				});
		alertDialog.show();
		
	}
	
	private void pay(Double totalPay, String orderStr) {
		UmiPaymentInfo paymentInfo = new UmiPaymentInfo();
		// TODO fix it
		paymentInfo.setAmount(1);
//		paymentInfo.setAmount(totalPay.intValue());
		paymentInfo.setCustomInfo(orderStr);
		paymentInfo.setSinglePayMode(true);
//		paymentInfo.setMinFee(totalPay.intValue());
		UmiPaySDKManager.showPayView(mContext, paymentInfo);
		
		showPayNotify = true;
		
		for (DbOrder order : orderList) {
			// 修改订单状态为待验证
			if (order.getOrderStatus() == CommConsts.Order.NONE_PAID) {
				orderService.markOrderWaitingPaid(mContext, order);
			}
		}
		
		orderAdapter.updateDataCache(orderList);
	}

	@Override
	public void onResume() {
		super.onResume();
		
		if (showPayNotify) {
			Toast.makeText(mContext, "因为供应商的关系，您的支付最迟在10分钟内完成，请耐心等待。", Toast.LENGTH_LONG).show();
			showPayNotify = false;
			
			launchCheckTask();
		}
	}

	private void launchCheckTask() {
		TaskInvoker orderCheckTask = new TaskCheckOrder(null, mContext);
		TaskQueue.add(orderCheckTask);
	}
	
	
}
